package com.xyh.transaction.utils;

import com.alibaba.fastjson.JSON;
import com.xyh.transaction.entity.dto.MessagesDTO;
import com.xyh.transaction.entity.dto.RequestMessageDto;
import com.xyh.transaction.entity.dto.ResponseMessageDto;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;

public class HttpUtil {

    // 发送GET请求
    public static String sendGet(String urlString, String authorizationHeader) throws Exception {
        StringBuilder result = new StringBuilder();
        URL url = new URL(urlString);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        if (authorizationHeader != null) {
            conn.setRequestProperty("Authorization", authorizationHeader);
        }

        try (BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()))) {
            String line;
            while ((line = in.readLine()) != null) {
                result.append(line);
            }
        }

        return result.toString();
    }

    // 发送POST请求
    public static String sendPost(String urlString, String jsonInputString, String authorizationHeader) throws Exception {
        StringBuilder result = new StringBuilder();
        URL url = new URL(urlString);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/json; utf-8");
        conn.setRequestProperty("Accept", "application/json");
        if (authorizationHeader != null) {
            conn.setRequestProperty("Authorization", authorizationHeader);
        }
        conn.setDoOutput(true);

        try (OutputStream os = conn.getOutputStream()) {
            byte[] input = jsonInputString.getBytes(StandardCharsets.UTF_8);
            os.write(input, 0, input.length);
        }

        try (BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"))) {
            String line;
            while ((line = in.readLine()) != null) {
                result.append(line);
            }
        }

        return result.toString();
    }

    // 测试方法
    public static void main(String[] args) {
        try {
            // 测试GET请求
            String authorizationHeader = "Bearer irvhOUpiUlGSUbKurNzX:fcOEbYOfEurFrEkXsxsR";
            String response = "";

            // 测试POST请求
            RequestMessageDto requestMessageDto = new RequestMessageDto();
            requestMessageDto.setModel("general");
            requestMessageDto.setStream(false);
            MessagesDTO messagesDTO = new MessagesDTO();
            messagesDTO.setRole("user");
            messagesDTO.setContent("来一个只有程序员能听懂的笑话");
            ArrayList<MessagesDTO> messagesDTOArrayList = new ArrayList<MessagesDTO>();
            messagesDTOArrayList.add(messagesDTO);
            requestMessageDto.setMessages(messagesDTOArrayList);
            response = sendPost("https://spark-api-open.xf-yun.com/v1/chat/completions", JSON.toJSONString(requestMessageDto), authorizationHeader);
//            System.out.println("POST Response: " + response);
            System.out.println(JSON.parseObject(response, ResponseMessageDto.class).getChoices().get(0).getMessage().getContent());

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
